<template>
	<div class="wrapper">
	  <!-- header部分 -->
	  <header>
		<p>在线支付</p>
	  </header>
	  <h3>订单信息：</h3>
	  <div class="order-info" v-if="orders && orders.business">
		<p>
		  {{ orders.business.businessName }}
		  <i class="fa fa-caret-down" @click="detailetShow"></i>
		</p>
		<p>&#165;{{ orders.orderTotal }}</p>
	  </div>
	  <div v-else class="loading">
		<p>正在加载订单信息...</p>
	  </div>
	  <ul class="order-detailet" v-show="isShowDetailet && orders && orders.list">
		<li v-for="item in orders.list" :key="item.odId">
		  <p>{{ item.food.foodName }} x {{ item.quantity }}</p>
		  <p>&#165;{{ item.food.foodPrice * item.quantity }}</p>
		</li>
		<li v-if="orders && orders.business">
		  <p>配送费</p>
		  <p>&#165;{{ orders.business.deliveryPrice }}</p>
		</li>
	  </ul>
	  <h3>支付方式：</h3>
	  <ul class="payment-type">
		<li @click="selectPaymentMethod('alipay')" :class="{ 'selected': selectedPaymentMethod === 'alipay' }">
		  <img src="../assets/alipay.png" />
		  <i class="fa fa-check-circle" v-show="selectedPaymentMethod === 'alipay'"></i>
		</li>
		<li @click="selectPaymentMethod('wechat')" :class="{ 'selected': selectedPaymentMethod === 'wechat' }">
		  <img src="../assets/wechat.png" />
		  <i class="fa fa-check-circle" v-show="selectedPaymentMethod === 'wechat'"></i>
		</li>
	  </ul>
	  <div class="payment-button">
		<button @click="confirmPayment" :disabled="!orders || !orders.business || isPaymentProcessing">
		  {{ isPaymentProcessing ? '支付处理中...' : '确认支付' }}
		</button>
	  </div>
	  <Footer></Footer>
	</div>
  </template>
  
  <script setup>
  import Footer from "../components/Footer.vue";
  import qs from "qs";
  import { useRouter, useRoute } from "vue-router";
  import { ref, inject, onMounted, onUnmounted } from "vue";
  
  const axios = inject("axios");
  const router = useRouter();
  const route = useRoute();
  
  const orderId = route.query.orderId;
  const orders = ref({ business: {}, list: [] });
  const isShowDetailet = ref(false);
  const selectedPaymentMethod = ref('alipay'); // 默认选择支付宝
  const isPaymentProcessing = ref(false); // 支付处理状态
  
  const init = () => {
	console.log('Payment页面初始化，订单ID:', orderId);
	axios
	  .post(
		"/api/OrdersController/getOrdersById", // 修复：添加/api/前缀
		qs.stringify({
		  orderId: orderId,
		})
	  )
	  .then((response) => {
		console.log('获取订单详情API响应:', response);
		orders.value = response; // 修复：直接使用response，因为axios拦截器已经返回了data
	  })
	  .catch((error) => {
		console.error('获取订单详情失败:', error);
		alert('获取订单信息失败，请重试！');
	  });
  };
  init();
  
  // 防止用户通过浏览器后退按钮离开支付页面
  const handlePopState = () => {
	if (confirm('您确定要离开支付页面吗？订单可能无法完成支付。')) {
	  router.push({ path: "/index" });
	} else {
	  // 如果用户选择不离开，重新添加历史记录
	  history.pushState(null, null, location.href);
	}
  };

  onMounted(() => {
	// 添加历史记录并设置监听
	history.pushState(null, null, location.href);
	window.addEventListener('popstate', handlePopState);
  });
  
  onUnmounted(() => {
	// 清理事件监听器
	window.removeEventListener('popstate', handlePopState);
  });
  
  const detailetShow = () => {
	isShowDetailet.value = !isShowDetailet.value;
  };

  // 选择支付方式
  const selectPaymentMethod = (method) => {
	console.log('选择支付方式:', method);
	selectedPaymentMethod.value = method;
  };

  // 获取支付方式显示名称
  const getPaymentMethodName = () => {
	return selectedPaymentMethod.value === 'alipay' ? '支付宝' : '微信支付';
  };

  // 确认支付
  const confirmPayment = () => {
	if (!orders.value || !orders.value.business) {
	  alert('订单信息加载中，请稍后重试！');
	  return;
	}

	if (isPaymentProcessing.value) {
	  return; // 防止重复点击
	}

	const paymentMethodName = getPaymentMethodName();
	
	if (!confirm(`确认使用${paymentMethodName}支付 ¥${orders.value.orderTotal} 吗？`)) {
	  return;
	}

	isPaymentProcessing.value = true;
	console.log('开始支付流程:', {
	  orderId: orderId,
	  paymentMethod: selectedPaymentMethod.value,
	  amount: orders.value.orderTotal
	});

	// 模拟支付过程
	simulatePayment();
  };

  // 模拟支付过程
  const simulatePayment = () => {
	const paymentMethodName = getPaymentMethodName();
	
	// 显示支付处理中的提示
	alert(`正在跳转到${paymentMethodName}支付页面...`);
	
	// 模拟支付延迟
	setTimeout(() => {
	  // 随机模拟支付成功或失败（90%成功率）
	  const isSuccess = Math.random() > 0.1;
	  
	  if (isSuccess) {
		// 支付成功，立即更新订单状态
		updateOrderStatus(2).then(updateSuccess => {
		  if (updateSuccess) {
			console.log('订单状态更新成功，准备跳转页面');
		  } else {
			console.warn('订单状态更新失败，但支付已成功');
		  }
		  
		  // 无论订单状态更新是否成功，都提示用户支付成功并询问跳转
		  if (confirm('支付成功！订单已完成。\n\n是否查看订单列表？')) {
			// 用户选择查看订单列表
			router.push({ 
			  path: '/orderList',
			  query: { 
				from: 'payment',
				orderId: orderId,
				status: 'success'
			  }
			});
		  } else {
			// 用户选择返回首页
			router.push({ path: '/index' });
		  }
		});
	  } else {
		// 支付失败
		alert('支付失败，请重试！');
		isPaymentProcessing.value = false;
	  }
	}, 2000); // 2秒后完成支付
  };

  // 更新订单状态
  const updateOrderStatus = (newStatus) => {
	console.log(`开始更新订单${orderId}状态为:`, newStatus);
	
	return axios.post('/api/OrdersController/updateOrderState', qs.stringify({
	  orderId: orderId,
	  orderState: newStatus
	})).then(response => {
	  console.log('订单状态更新成功:', response);
	  if (response > 0) {
		console.log(`订单${orderId}状态已成功更新为${newStatus}`);
		return true;
	  } else {
		console.error('订单状态更新失败，影响行数为0');
		return false;
	  }
	}).catch(error => {
	  console.error('订单状态更新API调用失败:', error);
	  return false;
	});
  };
  </script>
  
  <style scoped>
  /****************** 总容器 ******************/
  .wrapper {
	width: 100%;
	height: 100%;
  }
  
  /****************** 加载状态 ******************/
  .loading {
	width: 100%;
	padding: 8vw 4vw;
	text-align: center;
	color: #666;
	font-size: 4vw;
  }
  
  /****************** header部分 ******************/
  .wrapper header {
	width: 100%;
	height: 12vw;
	background-color: #0097ff;
	color: #fff;
	font-size: 4.8vw;
  
	position: fixed;
	left: 0;
	top: 0;
	z-index: 1000;
  
	display: flex;
	justify-content: center;
	align-items: center;
  }
  
  /****************** 订单信息部分 ******************/
  .wrapper h3 {
	margin-top: 12vw;
	box-sizing: border-box;
	padding: 4vw 4vw 0;
  
	font-size: 4vw;
	font-weight: 300;
	color: #999;
  }
  
  .wrapper .order-info {
	box-sizing: border-box;
	padding: 4vw;
	font-size: 4vw;
	color: #666;
  
	display: flex;
	justify-content: space-between;
	align-items: center;
  }
  
  .wrapper .order-info p:last-child {
	color: orangered;
  }
  
  /****************** 订单明细部分 ******************/
  .wrapper .order-detailet {
	width: 100%;
  }
  
  .wrapper .order-detailet li {
	width: 100%;
	box-sizing: border-box;
	padding: 1vw 4vw;
  
	display: flex;
	justify-content: space-between;
	align-items: center;
  }
  
  .wrapper .order-detailet li p {
	font-size: 3vw;
	color: #666;
  }
  
  /****************** 支付方式部分 ******************/
  .wrapper .payment-type {
	width: 100%;
  }
  
  .wrapper .payment-type li {
	width: 100%;
	box-sizing: border-box;
	padding: 4vw;
	cursor: pointer;
	transition: all 0.3s ease;
	border-bottom: 1px solid #f0f0f0;
  
	display: flex;
	justify-content: space-between;
	align-items: center;
  }
  
  .wrapper .payment-type li:hover {
	background-color: #f9f9f9;
  }
  
  .wrapper .payment-type li:active {
	background-color: #e6f7ff;
	transform: scale(0.98);
  }
  
  .wrapper .payment-type li.selected {
	background-color: #f0f8ff;
	border-left: 4px solid #38ca73;
  }
  
  .wrapper .payment-type li img {
	width: 33vw;
	height: 8.9vw;
  }
  
  .wrapper .payment-type li .fa-check-circle {
	font-size: 5vw;
	color: #38ca73;
	transition: all 0.3s ease;
  }
  
  .wrapper .payment-button {
	width: 100%;
	box-sizing: border-box;
	padding: 4vw;
  }
  
  .wrapper .payment-button button {
	width: 100%;
	height: 10vw;
	border: none;
	/*去掉外轮廓线*/
	outline: none;
	border-radius: 4px;
	background-color: #38ca73;
	color: #fff;
	font-size: 4.5vw;
	font-weight: 700;
	cursor: pointer;
	transition: all 0.3s ease;
  }
  
  .wrapper .payment-button button:hover:not(:disabled) {
	background-color: #2eb85c;
	transform: translateY(-1px);
  }
  
  .wrapper .payment-button button:disabled {
	background-color: #ccc;
	cursor: not-allowed;
	transform: none;
  }
  
  .wrapper .payment-button button:active:not(:disabled) {
	transform: translateY(0);
  }
  </style>
